package command;

import command.commandRunnable.CommandDataBaseCreator;
import command.commandRunnable.CommandJSonParser;
import command.commandRunnable.CommandXmlParser;
import logger.LoggerManager;
import resurses.LoggerMessage;

import java.util.*;

/**
 * Created by alexander.makalov on 24.10.2014.
 */
public class CommandLine implements Runnable {

    private static final String CREATE_DATABASE = "dbc";
    private static final String JSON_WORKER = "jw";
    private static final String XML_WORKER = "xw";

    public CommandLine(){
        usingScanner();

    }

    private void runCommand(List<String> name){
        switch (name.get(0)){
            case CREATE_DATABASE:
                CommandDataBaseCreator commandDataBaseCreator = new CommandDataBaseCreator();
                commandDataBaseCreator.run();
                break;
            case JSON_WORKER:
                CommandJSonParser commandJSonParser = new CommandJSonParser();
                commandJSonParser.setJSONFilePath(name.get(1));
                commandJSonParser.run();
                break;
            case XML_WORKER:
                CommandXmlParser commandXmlParser = new CommandXmlParser();
                commandXmlParser.setXmlFilePath(name.get(1));
                commandXmlParser.run();
        }
    }

    private void usingScanner()
    {
        //System.out.println("Command: ");

        Scanner scanIn = new Scanner(System.in);
        String inputString = scanIn.nextLine();
        scanIn.close();

        List<String> args = splitCommand(inputString);
        if (args.size()>0 &&contains(args.get(0))){
            runCommand(args);
        } else{
            LoggerManager.getLogger().Log(LoggerMessage.COMMAND_NOT_FOUND, LoggerManager.LogLevel.INFO);
        }
    }

    @Override
    public void run() {
        usingScanner();
    }

    private List<String> splitCommand(String inputString){
        String[] splitString = inputString.split(" ");
        List<String> strings = new ArrayList<>();
        for (int i = 0; i<splitString.length;i++){
            if (splitString[i].trim().length() !=0){
                strings.add(splitString[i].trim());
            }
        }
        return strings;
    }

    public enum CommandType{
        dbc,jw,xw;
    }

    public static boolean contains(String test) {
        if (test.length()>1){
            for (CommandType c: CommandType.values()) {
                if (c.name().equals(test)) {
                    return true;
                }
            }
        }
        return false;
    }
}
